<?php
namespace Admin\Controller;
use Think\Controller;
class PowerController extends Controller {

    public function __construct()
    {
        parent::__construct();
        if(empty($_SESSION['id'])){
            $this->redirect('Login/login');
        }else{
            if($_SESSION['rid']!='99'){
                $this->redirect('Login/login');
            }
        }
    }

    /**
     * 添加权限页面
     */
    public function power(){
        $info=M('merchant_power','','XYC');
        $list=$info->WHERE(['status'=>1,'version'=>2])->ORDER("weight asc")->SELECT();
        $list=get_new_arrays($list);

        $this->assign(array(
            'list'=>$list
        ));
        $this->display();
    }

    /**
     * 添加权限操作
     */
    public function add_power(){
        $info=M('merchant_power','','XYC');
        if(!empty($_POST)){
            $data['name']=I('name');
            $data['actionname']=I('actionname');
            $pid=I('pid');
            if(empty($pid)){
                $data['pid']='0';
                $data['level']='1';
            }else{
                $data['pid']=$pid;
                $level=$info->WHERE(['id'=>$pid])->getField('level');
                $data['level']=$level+1;
            }
            $data['ctime']=time();
            $data['version']=2;
            $res=$info->add($data);
            if($res){
                $info->WHERE(['id'=>$res])->setField('weight',$res);
                $this->ajaxReturn(['code'=>'1001','result'=>'添加成功']);
            }else{
                $this->ajaxReturn(['code'=>'1002','result'=>'添加失败']);
            }
        }
    }
    /**
     * 权限列表
     */
    public function power_list(){
        $info = M('merchant_power', '', 'XYC');
        $list = $info->WHERE("status=1 and version=2")->ORDER("weight asc")->SELECT();
        $list = get_new_arrays($list);

        $this->assign(array(
            'list' => $list,
        ));
        $this->display();
    }

    /**
     * 权限删除
     */
    public function del_power(){
        $info = M('merchant_power', '', 'XYC');
        if(!empty($_POST)){
            $pid=I('id');
            $res=$info->WHERE(['id'=>$pid])->setField('status','2');
            if($res!==false){
                $this->ajaxReturn(['code'=>'1001','result'=>'删除成功']);
            }else{
                $this->ajaxReturn(['code'=>'1002','result'=>'删除失败']);
            }
        }
    }

    /**
     * 修改权限名称
     */
    public function modify_power(){
        $info = M('merchant_power', '', 'XYC');
        if(!empty($_POST)){
            $name=I('name');
            $id=I('id');
            $res=$info->WHERE(['id'=>$id])->setField('name',$name);
            if($res!==false){
                $this->ajaxReturn(['code'=>'1001','result'=>'修改成功']);
            }else{
                $this->ajaxReturn(['code'=>'1002','result'=>'修改失败']);
            }
        }
    }

}